package Test.PracticeCAS;

import java.util.concurrent.atomic.AtomicInteger;

public class CasABADemo {

    //原子变量 AtomicInteger
    public static AtomicInteger a = new AtomicInteger(1);

    public static void main(String[] args) {

        Thread main = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "  " + a.get());

                int expectInt = a.get();
                int newInt = expectInt + 1;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                boolean compareAndSet = a.compareAndSet(expectInt, newInt);

                System.out.println(compareAndSet);
                System.out.println(a.get());
            }
        });


        Thread ganrao = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                a.incrementAndGet();
                System.out.println(a.get());
                a.decrementAndGet();
                System.out.println(a.get());
            }
        });

        main.start();
        ganrao.start();


    }

}